﻿using System.Windows;
using System.Windows.Controls;
using YY.Admin.Services.Service;
using YY.Admin.ViewModels.SysManage;

namespace YY.Admin.Views.SysManage
{
    /// <summary>
    /// UserManagementView.xaml 的交互逻辑
    /// </summary>
    public partial class UserManagementView : UserControl
    {
        public UserManagementView()
        {
            InitializeComponent();
            //this.Loaded += UserManagementView_Loaded;
        }

        //private void UserManagementView_Loaded(object sender, RoutedEventArgs e)
        //{
        //    if (DataContext is UserManagementViewModel viewModel)
        //    {
        //        Task.Run(viewModel.PaginationDataGridViewModel.LoadData);
        //    }

        //    // 记得取消事件订阅，避免重复执行
        //    this.Loaded -= UserManagementView_Loaded;
        //}

        // 在 Window 或 UserControl 的代码后台
        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is DataGrid dataGrid && dataGrid.DataContext is UserManagementViewModel viewModel)
            {
                // 获取所有新增选中的项
                foreach (var addedItem in e.AddedItems)
                {
                    if (addedItem is UserOutput user)
                    {
                        user.IsSelected = true;
                    }
                }

                // 获取所有取消选中的项
                foreach (var removedItem in e.RemovedItems)
                {
                    if (removedItem is UserOutput user)
                    {
                        user.IsSelected = false;
                    }
                }

                // 通知 ViewModel 更新状态
                viewModel.UpdateSelectionState();
            }
        }

        private async void ResetButton_Click(object sender, RoutedEventArgs e)
        {
            // 手动清除 DateTimePicker
            // TO-DO HC DateTimePicker控件存在Bug，这里需要显示地清除，Bug已修复已提交PR
            //BeginTimePicker.Text = string.Empty;
            //EndTimePicker.Text = string.Empty;

            // 通过反射获取内部 TextBox
            //var searchTextBoxField = typeof(AutoCompleteTextBox).GetField("_searchTextBox",
            //    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //if (searchTextBoxField?.GetValue(AutoCompleteTextBox) is System.Windows.Controls.TextBox textBox)
            //{
            //    // 直接清空内部 TextBox
            //    textBox.Text = string.Empty;
            //}

            //// 清空其他状态
            //AutoCompleteTextBox.SelectedItem = null;
            //AutoCompleteTextBox.SelectedIndex = -1;


            // 调用 ViewModel 的重置方法
            if (DataContext is UserManagementViewModel viewModel)
            {
                await viewModel.ResetFormAsync();
            }
        }
    }
}
